var _codeListData;
function getUrlPrefix(){
    return window.BASETATH;
}

function getWidgetObj(id){
    return window[id];
}
function ajax (uri, method, options,async) {
    var config ={
        url: getUrlPrefix() + uri,
        type: method,
        //contentType: 'application/json',
        cache: false,
        dataType: 'json',
        async:async,
        beforeSend: showLoading,
        complete: hideLoading,
        success: function(result){
            if(!result.suc && result.message == "没有登录"){
                window.location.href = window.BASETATH;
                return;
            }
            if(async) {
                options.success(result);
            }else{
                return result;
            }
        },
        error:function(jqXHR,textStatus,errorThrown){
            $('html').html(jqXHR.responseText)
        }
    }
    var data = handleData(options,method);
    if(data != {}){
        config.data = data;
    }
    $.ajax(config);
}
function showLoading() {
    //$("body").mask("正在处理中", null, false);
    //$("body").activateBox();
    window.Dialog.loading("");
}
function hideLoading() {
    //$("body").unmask();
    window.Dialog.closeLoading();
}
function handleData(options,method){
    var data = {};

    if(options.formId != undefined){
        var t =$('#'+options.formId).serializeArray()
        data = paramString2Obj(t);
    }

    if(options.data != undefined){
        if ($.isArray(options.data)) {
            data = [];
        }
        data = $.extend(data, options.data);
    }

    if(data != {}){
        //jquery GET的时候 data传入json对象 否则要传入字符串
        if(method !=RequestMethod.GET){
            var content = JSON.stringify(data)
            data = {};
            data.content = content;
        }else{
            data = data
        }
    }

    return data;
}
var restAjax = function(uri, method, options){ajax (uri, method, options,true) };
var restAjaxAsync =  function(uri, method, options){ajax (uri, method, options,false) };
var fielUploadAjax=function(uri,options){
    var data = handleData(options,RequestMethod.GET);
    var config = {
        url : getUrlPrefix() + uri,   //submit to UploadFileServlet
        secureuri : false,

        fileElementId : options.fileElementId,
        dataType : 'json', //or json xml whatever you like~
        success : function(data, status) {
            options.success(data)
        },
        error : function(data, status, e) {
            $("#result").append(data);
        }
    };
    if(data != {}){
        config.data = data
    }

    $.ajaxFileUpload(config);
}
var RequestMethod={GET:"GET",POST:"POST",PUT:"PUT",DELETE:"DELETE"}
var ButtonType={QUERY:"query",SAVE:"save",UPDATE:"update",DELETE:"delete"}
function paramString2Obj (a) {
    var o = {};
    $.each(a, function() {

        if (o[this.name]) {

            if (!o[this.name].push) {

                o[this.name] = [ o[this.name] ];

            }

            o[this.name].push(this.value || '');

        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
}

var _openDialog;
function openDialog(url,width,height,title,func){
    _openDialog = new Dialog();
    if(title != undefined){
        _openDialog.Title = title;
    }else{
        _openDialog.Title = "";
    }
    var actHeight = $(document).height();
    var actWidth = $(document).width();
    _openDialog.Drag = true;
    _openDialog.URL = getUrlPrefix() + url;
    _openDialog.Width=calcHW(width,actWidth);
    _openDialog.Height=calcHW(height,actHeight);
    if(func!= undefined){
        _openDialog.CancelEvent = func;
    }
    _openDialog.show();
}

function calcHW(orgNum,actNum){
    if(actNum >= orgNum ){
        return orgNum;
    }

    var percentNum = (orgNum/actNum).toFixed(2);

    var retNum = Math.floor(percentNum * actNum - 10);

    return retNum;
}

function closeDialog(){
    var diag = parent._openDialog;

    if(diag == undefined){
        diag = _openDialog
    }
    if(diag == undefined){
        Dialog.alert("未找到窗口对象")
    }else{
        diag.close();
    }
}

function _getGrid(){
    var grid;
    var gridId;
    if(window["_cusBindFormGirdId"] == undefined){
        gridId = parent["_cusBindFormGirdId"]
        grid = parent[gridId]
    }else{
        gridId = window["_cusBindFormGirdId"];
        grid = window[gridId];
    }

    return grid;
}



function evalFunc(func,param){
    if(func != undefined){
        func(param)
    }
}

function getFormData(formId){
    var t =$('#'+formId).serializeArray()
    var data = paramString2Obj(t);

    return data;
}

function joinData(sourceData,targetData){
    for(var id in sourceData){
        targetData[id] = sourceData[id];
    }
}

function setFormDataHandle(data){
    var codeNameArr = new Array();
    for(var id in data){
        var obj = $('#'+id);
        if(obj != undefined && obj != null){
            if(jQuery.isPlainObject(obj)){
                var codeNameArrTemp = setFormData(obj)
                for(var i = 0;i < codeNameArrTemp;i++){
                    codeNameArr.push(codeNameArr[i]);
                }
            }else{
                if(obj.attr("codeName") !== undefined){
                    var codeObj = {id:obj.attr("id"),codeName:obj.attr("codeName")};
                    codeNameArr.push(codeObj);
                }



                //日期处理
                var className = obj.attr("class");
                if(className !== undefined && className.indexOf("validate") == -1
                    &&className.indexOf("date") != -1){
                    if(data[id] != '0'){
                        if(obj.attr("dateFmt") !== undefined){
                            obj.val($.myTime.UnixToDate(data[id],true,8));
                        }else{
                            obj.val($.myTime.UnixToDate(data[id],false,8));
                        }
                    }
                }else{

                    if(!setCheckboxRadioValue(id,data[id])){
                            obj.val(data[id]);
                        if(obj["setValue"] != undefined){
                            obj.setValue(data[id]);
                        }

                    }

                }


            }
        }
    }

    return codeNameArr;
}
function setCheckboxRadioValue(id,value){
    var isCheckbox = false;

    $("input[name='"+ id +"']").each(
        function(){
            var checkboxObj = $(this);
            if(checkboxObj.attr("type") == "checkbox"){
                isCheckbox = true;
                var checkBoxItem = value.toString();

                var valArr = checkBoxItem.split(",");

                for(var i = 0;i < valArr.length;i++){
                    if(valArr[i] == checkboxObj.val()){
                        checkboxObj.attr("checked",true)
                    }
                }
            }else if(checkboxObj.attr("type") == "radio"){
                isCheckbox = true;
                if(value == checkboxObj.val()){
                    checkboxObj.attr("checked",true)
                }
            }


        }

    )

    return isCheckbox;
}
function setFormData(data){
    var codeNameArr = setFormDataHandle(data);

    if(codeNameArr.length > 0){
        $.codeCovert(codeNameArr);
    }
}

function validationForm(idArr){
    for(var i = 0;i < idArr.length;i++){
        var flag = $('#'+idArr[i]).validationEngine({returnIsValid: true});
        if(flag == false){
            return false;
        }
    }
    return true;
}

function validationFormSingle(id){
   return $('#'+id).validationEngine({returnIsValid: true});
}
/**
 * 判断是否进行过初始化
 * @param obj
 * @private
 */
function _initComboxValued(obj){
   if(obj.data("_initComboxValueFalg") == ""
       || obj.data("_initComboxValueFalg") == undefined) {
       obj.data("_initComboxValueFalg",1);
        return true;
   }else{
       return false;
   }
}
/**
 * 下拉框，数据初始化
 * @param url
 * @param param
 * @param codeType
 * @param obj
 */
function initComboxValue(url,param,codeType,obj){
    if(codeType != ""){
    var paramjson = _codeListData[codeType];
        var selData = {"list":paramjson};
        obj.data("data",selData);
        obj.render();
    }else if(url != "" && param!= ""){
        restAjax(url,RequestMethod.GET,{
            data:JSON.parse(param),
            success: function (data) {
                if (data  != "") {
                    obj.data("data",data);
                    obj.render();
                }
            }
        });
    }else if(url != "" && param == ""){
        restAjax(url,RequestMethod.GET,{
            success: function (data) {
                if (data  != "") {
                    obj.data("data",data);
                    obj.render();
                }
            }
        });
    }else if(url == "" && param != ""){
        var selData = {"list":JSON.parse(param)};
        obj.data("data",selData);
        obj.render();
    }
}

/**
 * 下拉树，数据初始化
 * @param url
 * @param param
 * @param obj
 */
function initComboxTreeValue(url,param,obj){
    if(param == ""){
        restAjax(url,RequestMethod.GET,{
            success: function (data) {
                renderComboxTreeData(data,obj);
            }
        });
    }else{
        restAjax(url,RequestMethod.GET,{
            data:JSON.parse(param),
            success: function (data) {
                renderComboxTreeData(data,obj);
            }
        });
    }
}

function renderComboxTreeData(data,obj){
    if(data != ""){
        var treeNodes = data['treeNodes'];
        if(treeNodes != null && treeNodes.length>0){
            obj.data("data",data);
            obj.render();
        }
    }
}
/**
 * 页面转换字典表id为name
 * @param rowdata
 * @param rowindex
 * @param value
 * @param column
 * @param codeType
 * @returns {*}
 */
function codeTypeConvert(rowdata, rowindex, value, column,codeType){
    var paramjsonArr = _codeListData[codeType];

    for(var i = 0;i < paramjsonArr.length;i++){
        var values = paramjsonArr[i].value;

        if(values == value){
            return paramjsonArr[i].key;
        }
    }
}
/***************************导出方法 START***************************************/
/**
 * 导出GRID全部数据
 */
function exportTotalData(item){
    exportCore('/CommonCoreController/exportAllData',item);
}
/**
 * 导出GRID当前页数据
 */
function exportPageData(item){
    exportCore('/CommonCoreController/exportPageData',item);
}
/**
 * 导出方法
 * @param expurl
 */
function exportCore(expurl,item){
    var _grid =  window[item.gridid];
    var showColumn =   _getShowColumn(_grid.id, _grid._columns);
    var expformId = _grid.id+"Exp";

    fielUploadAjax(expurl,{
        data:{headershowFields:showColumn},
        formId:expformId,
        success: function (data) {

        }
    });
}
/**
 * 导出使用，获取列对象
 * @param gridId
 * @param column
 * @returns {string}
 * @private
 */
function _getShowColumn(gridId,column){
    var showColumn = "";
    for(var obj in column){
        if(!column[obj]._hide){
            showColumn += column[obj].id + "|";
        }
    }
    return showColumn;
}
/***************************导出方法 end***************************************/

function unselectButton(rowdata, rowindex, value, column){
    return '<div class="padding_top4 padding_left5">'
        + '<span class="img_btn_right hand" onclick="unselectItem(\'' + rowdata.id + '\',\''+rowindex + '\')"></span>'
        + '</div>'
}

function selectButton(rowdata, rowindex, value, column){
    return '<div class="padding_top4 padding_left5">'
        + '<span class="img_btn_left hand"  onclick="selectItem(\'' + rowdata.id + '\',\''+rowindex + '\')"></span>'
        + '</div>'
}

/**
 * GRID列内容略缩，气泡显示完整内容
 * @param rowdata
 * @param rowindex
 * @param value
 * @param column
 * @returns {string}
 * @private
 */
function _gridColoumnTipLite(rowdata, rowindex, value, column){
    return "<span class=\"textSlice\"  title=\" "+ value + "\">" + value + "</span>";
}
/**
 * 转换时间戳为日期格式
 * @param nS
 * @returns {string|*}
 */
function getLocalTime(nS) {
    return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}


/*********************导出excel开始***************************/
/*导出当前*/
function exportCurrent(g){
    if(g.getData().length == 0){
        top.Dialog.alert("grid表格没有数据 ,无法执行导出操作!");
        return false;
    }
    var subCols = getCols(g);
    var str = JSON.stringify(makeExpObj(g,subCols));

    downloadFile({mess:str},"/excel/current/")
}
/*导出全部*/
function exportAll(g){
    if(g.getData().length == 0){
        top.Dialog.alert("grid表格没有数据 ,无法执行导出操作!");
        return false;
    }
    var subCols = getCols(g);
    var str = JSON.stringify(makeExpObj(g,subCols));

    downloadFile({mess:str},"/excel/all/")
}

/**
 * 设置列参数
 * @param g
 * @returns {Array}
 */
function getCols(g){
    var cols = g.columns;
    var subCols = new Array();

    cols.forEach(function(col){
        if(col.display !== undefined && col.isExport != false){
            var subCol = {
                id:col.name,title:col.display
            }

            subCols.push(subCol)
        }

    })

    return subCols;
}
/**
 * 设置参数
 * @param g
 * @param subCols
 * @returns {{col: *, page: (*|g.page|jQuery.quiDefaults.Grid.page|myEditorGrid.page|page|hs.page), total: (*|g.total|Music.total|total|H.tooltipText.total|str.total), pageSize: *, url: *}}
 */
function makeExpObj(g,subCols){
    var gridOptions = g.options;
    var total = gridOptions.total;
    var page = gridOptions.page;
    var pageSize = gridOptions.pageSize;
    var url = gridOptions.url;

    var params = gridOptions.params;

    var obj = {col: subCols, page: page, total: total, pageSize: pageSize, url: url};

    return obj;
}

/*********************导出excel结束***************************/
/**
 * 下载文件
 * @param params 请求参数
 * @param url    请求url
 */
function downloadFile(params,url){
    if(jQuery("#_fileDownloadForm") !== undefined )
        jQuery("#_fileDownloadForm").remove();
    var form = jQuery('<form  action="" method="POST" name="_fileDownloadForm" id="_fileDownloadForm"></form>');

    form.attr('style','display:none');   //在form表单中添加查询参数
    form.attr('target','');
    form.attr('action',getUrlPrefix() +url);

    $('body').append(form);  //将表单放置在web中

    if(params)
    {
        for(var i in params)
        {
            jQuery('<input type="hidden" name="' + i + '" id="' + i + '" />').appendTo(form);
            jQuery('#'+i).val(params[i])
        }
    }


    form.submit();   //表单提交
}





